document.writeln("<script type='text/javascript' src='utils.js'></script>");


var run_chat = self.setInterval(function(){submit_chat("");},1000);
var player= "";	
var otherPlayer ="";

var turn_ended;
if(turn_ended)
	turn_ended =	self.setInterval(function(){check_if_my_turn("");},700);


var clicked = false;
var moved = 0;
var boardT =	"1:1:1:0:0:0:0:0:" +
 				"1:1:0:0:0:0:0:0:" +
 				"1:0:0:0:0:0:0:0:" +
 				"0:0:0:0:0:0:0:0:" +
 				"0:0:0:0:0:0:0:0:" +
 				"0:0:0:0:0:0:0:2:" +
 				"0:0:0:0:0:0:2:2:" +
 				"0:0:0:0:0:2:2:2:";


addLoadEvent(iniBoard);
addLoadEvent(updateBoard);



function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		};
	}
}

function iniBoard() {
	var board = document.createElementNS("http://www.w3.org/2000/svg", "svg");
	board.setAttribute("style", "background: red");
	board.setAttribute("height", "470");
	board.setAttribute("width", "470");
	document.getElementById("boardplace").appendChild(board);
	for (var i=0;i<8;i++)
	{
		for (var j=0;j<8;j++)
		{
			var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
			shape.setAttribute("id", i +"-"+ j);
			shape.setAttribute("onmousedown","mouse_down(evt)");
			shape.setAttribute("onclick","mouse_click(evt)");
			shape.setAttribute("onmouseup","mouse_up(evt)");
			shape.setAttribute("cx", 40 + i*55);
			shape.setAttribute("cy", 40 + j*55);
			shape.setAttribute("r",  20);
			shape.setAttribute("fill", "white");
			shape.setAttribute("class", "piece");
			board.appendChild(shape);
		}
	}
}

function updateBoard() {
	var tmp = boardT.split(":");
	for(var i=0;i<8;i++) {
		for(var j=0;j<8;j++) {	
			var idToStr = (i*8)+j;
			var place = i +"-"+ j;
			if(tmp[idToStr]==0)
				document.getElementById(place).setAttribute("class","piece" );
			if(tmp[idToStr]==1)
				document.getElementById(place).setAttribute("class","firstP" );
			if(tmp[idToStr]==2)
				document.getElementById(place).setAttribute("class", "secondP");
		}
	}
}

function check_if_my_turn() {
//	var xmlhttp;
	if (window.XMLHttpRequest)	// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	else // code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			var str = xmlhttp.responseText.substring(0,5);
			   if(str=="turn$") {
				   var ans = xmlhttp.responseText.slice(5);
				if ( ans !="false") {
					turn_ended = self.clearInterval(turn_ended);
					boardT =  ans;//xmlhttp.responseText;
//					updateBoard();
					turn_ended = false;
					switch_sides(false);
					reset_board("");
					return;
				}
			} 
		}
	};
	xmlhttp.open("Post","GameManager",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("&my_turn=true");	
}

function submit_move()
{
	
	turn_ended = true;
	var xmlhttp;
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else
    {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			var str = xmlhttp.responseText.substring(0,5);
			   if(str=="move$") {
				   var ans = xmlhttp.responseText.slice(5);
				   answer = ans.split("$");
				   if (answer[0]== "turn_end") {
					   boardT =  answer[1];
					   switch_sides(true);
					   reset_board("");
					   updateBoard();
					   //switch_sides(true);
					   turn_ended =	self.setInterval(function(){check_if_my_turn("");},800);

					   //turn_ended =	self.setInterval(function(){check_if_my_turn("");},1000);

					   return;
				   }else if (answer[0]== "not_valid") {
					   //set board to given board 
					   document.getElementById("cturn").innerHTML = answer[1];
					   document.getElementById("moves").value = "";
					   window.boardT =  answer[2];
					   alert(window.boardT);
					   reset_board("");
					   turn_ended = false;
					   return;
				   }
			   }
		}
	};
	xmlhttp.open("Post","GameManager",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("&moves=" + document.getElementById("moves").value);

	document.getElementById("moves").value = "";
	
}

function switch_sides(cond) {
	if(cond)
		document.getElementById("cturn").innerHTML = "turn ended, waiting for other player to move";
	else
		document.getElementById("cturn").innerHTML = "It is your turn";
}

function reset_board() {
	clicked = false;
	moved = 0;
	updateBoard();
}

function mouse_click(evt)
{		
	if (turn_ended )
		return;
	if (! clicked )
	{
		clicked = evt.target["id"];
		mouse_down(evt);
		return;
	}	
	else if (evt.target["id"] == clicked)
		return;		 
	mouse_up(evt);
	return;
}
	
	function mouse_down(evt)
	{
		 if (turn_ended) 
			 return;
		 if (evt.target["class"] == otherPlayer)
			 return;
		 if (moved ==2 && evt.target["id"] != clicked)
			 return;
		 if (evt.target.getAttribute("class")!= player)
		 	 return;
		 clicked = evt.target["id"];
	 	 evt.target.setAttribute("class", "pushed");
	}
	
	function mouse_up(evt)
	{
		if (turn_ended || clicked==false )
			return;
		 if (evt.target["class"] == otherPlayer ||  document.getElementById(clicked).getAttribute("class") == otherPlayer)
			 return;
		document.getElementById(clicked).setAttribute("class", "piece");
		from = clicked;
		to = evt.target["id"];
		if (! valid_move(from, to) ) 
		{
			if (moved ==0)
			{
				document.getElementById(clicked).setAttribute("class", player);

				clicked = false;
			}else if (moved ==2)
			{
				document.getElementById(clicked).setAttribute("class", "pushed");
			}
			return;
		}
		var from_obj = document.getElementById(from);
		from_obj.setAttribute("class", "piece");
		
		var to_obj = document.getElementById(to);
		to_obj.setAttribute("class", player);
		
		document.getElementById("moves").value += from + "->"+ to + ";";
		clicked = to;
		evt.target.setAttribute("class", "pushed");
	}
	
	function submit_chat(chat_line)
	{
		first = false;
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
	    {// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	    }
		
		xmlhttp.onreadystatechange=function()
		{
		   if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
			   var str = xmlhttp.responseText.substring(0,5);
			   if(str=="chat$") {
				   var ans = xmlhttp.responseText.slice(5);
					   document.getElementById("chat_window").value =ans;// xmlhttp.responseText;
				   if (chat_line != "")
				   {
					   document.getElementById("chat_new_line").value="";
				   }
			   }
			}
		};
		xmlhttp.open("Post","GameManager",true);
		xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xmlhttp.send("&chat=" + chat_line);
	}
	
	function get_statistics()
	{
		var user = document.getElementById("user").getAttribute("value"); 
		var password = document.getElementById("password").getAttribute("value"); 
	    var form = document.createElement("form");
	    form.setAttribute("method", "post");
		form.setAttribute("action", "show_statistics");
		params={'user': user,'pass': password};

		for(var key in params) {
		    if(params.hasOwnProperty(key)) {
		        var hiddenField = document.createElement("input");
		        hiddenField.setAttribute("type", "hidden");
		        hiddenField.setAttribute("name", key);
		        hiddenField.setAttribute("value", params[key]);
		        form.appendChild(hiddenField);
		     }
		}
		document.body.appendChild(form);
		form.submit();
	}
	
	
	function player_resign()
	{
		//todo - player give up - game ends and other player gets score
	}	
	
	

	function valid_move(from, to)
	{		
		//check different cases
		if (from == false) 
			return false;
		if (turn_ended)
			return false;
		if (clicked && clicked == to)
			return false;

		if (document.getElementById(to).getAttribute("class") != "piece")
			return false;
		if (document.getElementById(from).getAttribute("class") == otherPlayer) 
			return false;

		var a = from.split("-");
		var b = to.split("-");
		var x1 = parseInt(a[0]);
		var y1 = parseInt(a[1]);
		var x2 = parseInt(b[0]);
		var y2 = parseInt(b[1]);


		// HANDLE MOVED ONE:
		if (  ( (Math.abs(x1 - x2) == 1) && (Math.abs(y1 - y2) <= 1)) 
			||( (Math.abs(y1 - y2) == 1) && (Math.abs(x1 - x2) == 0)) )
				{
					if (moved == 2)
						return false; //can't move one after moved two
					clicked = to;
					moved = 1;
					turn_ended = true;
						return true;
				}
		
		//HANDLE MOVED TWO:
		if ( ((Math.abs(x1 - x2) == 2) && (Math.abs(y1 - y2) == 0)) ||
		     ((Math.abs(x1 - x2) == 0) && (Math.abs(y1 - y2) == 2)) ||
		     ((Math.abs(x1 - x2) == 2) && (Math.abs(y1 - y2) == 2)) )
		{
			var p_id =  (x1+x2)/2 + "-" + (y1+y2)/2;
			if (document.getElementById(p_id).getAttribute("class") != "piece") 
			{
				clicked = to;
				moved=2;	
				return true;
			}
			return false;
		}
		//other (if exists):	
		return false;
	}
	
	function update_colors(from, to)
	{
		
		
	}
	function game_rules()
	{
		alert(
		"this game designed for two players.\n\n"+
		"In each turn the player can move one of his pieces to an empty spot,"+
		"one up|down|diagonaly\n"+
		"or two up|down|diagonaly if there is a piece in the middle."		
		);
	}

	
	
	